﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using AssetManagementSystem.Model;

namespace AssetManagementSystem.View.Controls {
    public partial class UIEmail : Form {

        SysPropertyManager manager;

        public UIEmail() {
            manager = new SysPropertyManager();
            InitializeComponent();
            RefreshSettings();
        }


        private void RefreshSettings() {
            txtFromAddress.Text = manager.GetProperty("FromAddress");
            txtBody.Text = manager.GetProperty("EmailTemplate");
            txtFromName.Text = manager.GetProperty("FromName");
            txtPassword.Text = manager.GetProperty("FromPassword");
            txtSMTPHost.Text = manager.GetProperty("SmtpHost");
            txtSMTPPort.Text = manager.GetProperty("SmtpPort");
            txtSubject.Text = manager.GetProperty("EmailSubject");
            txtUsername.Text = manager.GetProperty("FromUsername");
            //check if the smpt setting is the string 'true'
            chkSSL.Checked = manager.GetProperty("SmtpSSL").ToLower() == "true";
        }

        private void btnCancel_Click(object sender, EventArgs e) {
            this.Close();
        }

        private void btnSave_Click(object sender, EventArgs e) {
            try {
                manager.UpdateProperty("FromAddress", txtFromAddress.Text);
                manager.UpdateProperty("EmailTemplate", txtBody.Text);
                manager.UpdateProperty("FromName", txtFromName.Text);
                manager.UpdateProperty("FromPassword", txtPassword.Text);
                manager.UpdateProperty("SmtpHost", txtSMTPHost.Text);
                try {
                    int check = Convert.ToInt32(txtSMTPPort.Text);
                    manager.UpdateProperty("SmtpPort", check.ToString());
                } catch (Exception formatException) {
                    MessageBox.Show("Invalid SMTP port not stored.");
                }
                manager.UpdateProperty("EmailSubject", txtSubject.Text);
                manager.UpdateProperty("FromUsername", txtUsername.Text);
                if (chkSSL.Checked) {
                    manager.UpdateProperty("SmtpSSL", "true");
                } else {
                    manager.UpdateProperty("SmtpSSL", "false");
                }
                MessageBox.Show("Settings Saved");
            } catch (Exception saveException) {
                MessageBox.Show("Error: " + saveException.Message);
            }
            
        }

    }
}
